package com.incom.log.server.monitor;

import com.incom.log.server.conf.ServiceConfig;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public abstract class ServiceMonitor implements Runnable {

    private static List<ServiceMonitor> serviceMonitors = new ArrayList<>();

    public abstract void stopMonitor() throws Exception;

    public abstract void initMonitor(Properties properties) throws Exception;

    public abstract void startMonitor() throws Exception;

    public synchronized static void loadMonitor(Properties propertites) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        if(!serviceMonitors.isEmpty()) {
            return;
        }
        serviceMonitors.add(new ServiceMonitor() {
            @Override
            public void run() {
                try {
                    while(ServiceConfig.serverRunSts) {
                        Thread.sleep(1000);
                    }
                    Thread.sleep(5000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.exit(0);
            }

            @Override
            public void stopMonitor() throws Exception {}

            @Override
            public void initMonitor(Properties properties) throws Exception {}

            @Override
            public void startMonitor() throws Exception {
                new Thread(this).start();
            }
        });
        String property = propertites.getProperty("log-monitor.type");
        String[] split = property.split(",");
        for(String c : split) {
            Class<?> aClass = Class.forName(c);
            ServiceMonitor monitor = (ServiceMonitor) aClass.newInstance();
            serviceMonitors.add(monitor);
        }
    }

    public static List<ServiceMonitor> getServiceMonitors() {
        return serviceMonitors;
    }
}
